package com.tanhua.server.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tanhua.common.exception.BusinessException;
import com.tanhua.common.mapper.UserInfoMapper;
import com.tanhua.dubbo.server.api.SoundApi;
import com.tanhua.dubbo.server.pojo.Sound;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.common.vo.ErrorResult;
import com.tanhua.oss.OssTemplate;
import com.tanhua.server.vo.SoundVo;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.Date;
import java.util.List;

@Service
public class PeachblossomService {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private OssTemplate ossTemplate;
    @Reference
    private SoundApi soundApi;


    /**
     * 发送语音
     */
    public Boolean sendPeachblossom(MultipartFile soundFile) {
        User user = UserThreadLocal.get();

        //创建redis语音键(传音只能10次)
        //在redis里设置一个唯一的缓存键，根据当天的时间设置，并且根据下面的清除缓存设置清除
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String dateTime = simpleDateFormat.format(date);
        String key = user.getId() + "_" + dateTime + "_SEND_SOUND";

        //判断
        String keyValue = redisTemplate.opsForValue().get(key);
        if (null == keyValue) {
            //如果redis中没有就存入,key=id_time_SEND_SOUND;value=9
            redisTemplate.opsForValue().set(key, "9", Duration.ofDays(1));
        } else if (keyValue.equals("0")) {
            return false;
        } else {
            //每次递减1
            redisTemplate.opsForValue().decrement(key);
            //redisTemplate.boundValueOps(key).increment(-1L);
        }

        //redis有次数则根据id查询用户信息
        UserInfo userInfo = userInfoMapper.selectById(user.getId());
        Sound sound = new Sound();
        sound.setUserId(userInfo.getId());  //id
        sound.setGender(userInfo.getSex().name());  //性别
        try {
            //把声音文件上传到oss上，把sound文件保存到MongoDB上，两种同时成功，返回true给controller
            //上传语音
            String filePath = ossTemplate.upload(soundFile);
            sound.setSoundUrl(filePath);    //语音文件地址
            //保存
            this.soundApi.saveSound(sound);
            return true;
        } catch (Exception e) {
            throw new BusinessException(ErrorResult.sound());
        }
    }

    /**
     * 接收语音
     * 随机查询一个语音消息返回，在听完语音后，可以选择喜欢或者不喜欢，
     * 如果双方互相喜欢那么可以配对成功互相关注。
     * @return
     */
    public SoundVo querySound() {
        User user = UserThreadLocal.get();
        //判断他的接收次数
        //创建redis键(接收传音每天只能10次)
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String dateTime = simpleDateFormat.format(date);
        //记当天的接收次数
        String key = user.getId() + "_" + dateTime + "_GET_SOUND";

        //判断
        String keyValue = redisTemplate.opsForValue().get(key);
        if (null == keyValue) {
            redisTemplate.opsForValue().set(key, "9", Duration.ofDays(1));
        } else if (keyValue.equals("0")) {
            return null;
        } else {
            redisTemplate.opsForValue().decrement(key);

        }

        //获取到所有人声音文件的集合
        List<Sound> sounds = soundApi.querySounds();

        //通过createSoundUserId方法，传入sounds和当前用户的对象，随机获取非当前用户的传音
        Sound sound = createSoundUserId(sounds, userInfoMapper.selectById(user.getId()));
        UserInfo userInfo =userInfoMapper.selectById(user.getId());

        //返回响应
        SoundVo soundVo = new SoundVo();
        soundVo.setUserId(sound.getUserId());
        soundVo.setAvatar(userInfo.getLogo());
        soundVo.setNickname(userInfo.getNickName());
        soundVo.setGender(userInfo.getSex().name());
        soundVo.setAge(userInfo.getAge());
        soundVo.setSoundUrl(sound.getSoundUrl());
        int count = Integer.parseInt(redisTemplate.opsForValue().get(key));
        soundVo.setRemainingTimes(count);
        return soundVo;

    }


    /**
     * 随机获取非当前用户的传音
     * 排除自己的和已获取过的
     *
     * @param sounds
     * @param userInfo
     * @return
     */
    private Sound createSoundUserId(List<Sound> sounds, UserInfo userInfo) {
        //获得任意一个sound声音对象
        Sound sound = sounds.get(RandomUtils.nextInt(0, sounds.size() - 1));

        //判断,非自己,异性,不重复
        if (sound.getUserId() == userInfo.getUserId()
                || sound.getGender().equals(userInfo.getSex().name())) {
            if(redisTemplate.opsForHash().hasKey("sound", sound.getSoundUrl())==null){
                redisTemplate.opsForHash().put("sound", sound.getSoundUrl(), "0");
                return sound;
            }else if(redisTemplate.opsForHash().hasKey("sound", sound.getSoundUrl())){
                createSoundUserId(sounds, userInfo);
            }
        }
        redisTemplate.opsForHash().put("sound", sound.getSoundUrl(), "0");
        return sound;
    }

}
